<template>
  <a-modal
    :title="title"
    v-model="show"
    :maskClosable="false"
    :width="1050"
    placement="right"
    :closable="true"
    @cancel="onClose"
    :footer="null"
    :visiable="acctEntryOperationVisiable"
  >
    <a-form :form="form">
      <a-row>
        <a-col :md="12" :sm="24">
          <a-form-item label="会计分录标识"
                       v-bind="formItemLayout">
            <a-input v-decorator="['acctEntryId']" placeholder="系统自动生成" :disabled="true"/>
          </a-form-item>
          <a-form-item label="id"
                       v-bind="formItemLayout" style="display: none">
            <a-input v-decorator="['id']"/>
          </a-form-item>
          <a-form-item style="display: none">
            <a-input type="hidden" name="acctEntryId" v-decorator="['acctEntryId']"/>
          </a-form-item>
          <a-form-item style="display: none">
            <a-input type="hidden" name="auditStatus" v-decorator="['auditStatus']"/>
          </a-form-item>
          <a-form-item style="display: none">
            <a-input type="hidden" name="oprId" v-decorator="['oprId']"/>
          </a-form-item>
          <a-form-item style="display: none">
            <a-input type="hidden" name="oprStatus" v-decorator="['oprStatus']"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item label="会计分录描述"
                       v-bind="formItemLayout">
            <a-input v-decorator="['acctEntryDesc',{rules: [{ required: true, message: '必填' }]}]"
                     :disabled="this.isUpd"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="24" v-show="this.isStop == true">
          <a-form-item label="停用原因"
                       v-bind="formItemLayout">
            <a-input v-decorator="['stopReason',{rules: [{ required: this.isStop, message: '必填' }]}]"/>
          </a-form-item>
        </a-col>

        <a-col :md="12" :sm="24" v-show="this.isCancel == true">
          <a-form-item label="注销原因"
                       v-bind="formItemLayout">
            <a-input v-decorator="['cancelReason',{rules: [{ required: this.isCancel, message: '必填' }]}]"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <div>
          <div class="operator" v-show="this.title == '新增会计分录' || this.title == '修改会计分录'">
            <a-button ghost type="primary" @click="addAcctEntry">新增</a-button>
          </div>
          <!-- 表格区域 -->
          <a-table ref="TableInfo"
                   :columns="columns"
                   :rowKey="record => record.id"
                   :dataSource="dataSource"
                   :pagination="pagination"
                   :loading="loading"
                   :scroll="{ x: 2000 }"
                   @change="handleTableChange">
            <template slot="email" slot-scope="text, record">
              <a-popover placement="topLeft">
                <template slot="content">
                  <div>{{text}}</div>
                </template>
                <p style="width: 150px;margin-bottom: 0">{{text}}</p>
              </a-popover>
            </template>
            <template slot="acctEntryOperation" slot-scope="text, record, index">
              <a-icon type="setting" theme="twoTone" twoToneColor="#4a9ff5"
                      @click="editAcctEntry(record)" title="修改"></a-icon>&nbsp;
              <a-icon type="delete" theme="twoTone" twoToneColor="#42b983"
                      @click="delAcctEntry(record,index)" title="删除"></a-icon>
            </template>
          </a-table>
        </div>
      </a-row>
    </a-form>
    <div class="firstColAdd" v-show="this.title !== '详情'">
      <a-button @click="onClose" type="primary">取消</a-button>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>

    <div>
      <!-- 新增或修改 -->
      <acct-entry-add-edit
        ref="acctEntryAddEdit"
        @close="handleAcctEntryAddEditClose"
        @success="handleAcctEntryAddEditSuccess"
        :acctEntryAddEditVisiable="acctEntryAddEdit.visiable">
      </acct-entry-add-edit>
    </div>
  </a-modal>
</template>
<script>
  const formItemLayout = {
    labelCol: {span: 8},
    wrapperCol: {span: 16}
  }

  import AcctEntryAddEdit from "./AcctEntryAddEdit";

  export default {
    name: 'AcctEntryOperation',
    components: {AcctEntryAddEdit},
    props: {
      acctEntryOperationVisiable: {
        default: false
      },
      instId: '',
    },
    data() {
      return {
        title: '新增会计分录',
        isStop: false,
        isCancel: false,
        isUpd: false,
        loading: false,
        formItemLayout,
        form: this.$form.createForm(this),
        validateStatus: '',
        acctEntryAddEdit: {
          visiable: false
        },
        info: {
          infoName: '',
          remark: '',
          menuId: ''
        },
        optFlagTmp: 'add',
        dataSource: [],
        sortedInfo: null,
        paginationInfo: null,
        // selectedRowKeys: [],
        pagination: {
          pageSizeOptions: ['10', '20', '30', '40', '100'],
          defaultCurrent: 1,
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
        },

      }
    },
    computed: {
      show: {
        get: function () {
          return this.acctEntryOperationVisiable
        },
        set: function () {
        }
      },
      columns() {
        let {sortedInfo} = this
        sortedInfo = sortedInfo || {}
        let {filteredInfo} = this
        filteredInfo = filteredInfo || {}
        return [{
          title: '序号',
          dataIndex: 'groupNo',
          width: 70,
          scopedSlots: {customRender: 'groupNo'},
        }, {
          title: '借方科目',
          dataIndex: 'settleAcctIdD',
          scopedSlots: {customRender: 'settleAcctIdD'},
        }, {
          title: '借方科目描述',
          dataIndex: 'settleAcctDescD',
          scopedSlots: {customRender: 'settleAcctDescD'},
        }, {
          title: '借方科目金额方向',
          dataIndex: 'amountDirectionD',
          customRender: (text, row, index) => {
            switch (text) {
              case '+':
                return '正金额'
              case '-':
                return '负金额'
              default:
                return text
            }
          }

        }, {
          title: '借方清算角色',
          dataIndex: 'settleRoleD',
          customRender: (text, row, index) => {
            switch (text) {
              case '01':
                return '总行'
              case '02':
                return '发卡分行'
              case '03':
                return '发卡支行'
              case '04':
                return '收单分行'
              case '05':
                return '收单支行'
              case '10':
                return '商户'
              default:
                return text
            }
          },
        }, {
          title: '贷方科目',
          dataIndex: 'settleAcctIdC',
          scopedSlots: {customRender: 'settleAcctIdC'},
        }, {
          title: '贷方科目描述',
          dataIndex: 'settleAcctDescC',
          width: 200,
          scopedSlots: {customRender: 'settleAcctDescC'},
        }, {
          title: '贷方科目金额方向',
          dataIndex: 'amountDirectionC',
          customRender: (text, row, index) => {
            switch (text) {
              case '+':
                return '正金额'
              case '-':
                return '负金额'
              default:
                return text
            }
          }
        }, {
          title: '贷方清算角色',
          dataIndex: 'settleRoleC',
          customRender: (text, row, index) => {
            switch (text) {
              case '01':
                return '总行'
              case '02':
                return '发卡分行'
              case '03':
                return '发卡支行'
              case '04':
                return '收单分行'
              case '05':
                return '收单支行'
              case '10':
                return '商户'
              default:
                return text
            }
          }
        }, {
          title: '操作',
          dataIndex: 'acctEntryOperation',
          fixed: 'right',
          width: 100,
          show: false,
          scopedSlots: {customRender: 'acctEntryOperation'}
        }]
      }
    },
    mounted() {
      this.fetch()
    },

    methods: {

      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },

      addAcctEntry() {
        let acctEntryDesc = this.form.getFieldsValue(['acctEntryDesc'])
        var record = {};
        record.instId = this.instId;
        let groupNoTmp = 0
        if (this.dataSource.length != 0) {
          groupNoTmp = this.dataSource[this.dataSource.length - 1].groupNo + 1
        }
        var groupNo = this.dataSource.length <= 0 ? 0 : groupNoTmp;
        record.groupNo = groupNo
        record.id = groupNo

        record.optFlag = 'add'
        if (acctEntryDesc.acctEntryDesc) {
          this.acctEntryAddEdit.visiable = true
          this.$refs.acctEntryAddEdit.setAcctEntryFormRecordValues(record);
        } else {
          this.$message.warning("请先填写会计分录描述！");
        }
      },


      editAcctEntry(record) {
        if (this.title == '新增会计分录' || this.title == '修改会计分录') {
          let acctEntryDesc = this.form.getFieldsValue(['acctEntryDesc'])
          record.optFlag = 'upd'
          if (acctEntryDesc.acctEntryDesc) {
            this.acctEntryAddEdit.visiable = true
            this.$refs.acctEntryAddEdit.setAcctEntryFormRecordValues(record);
          } else {
            this.$message.warning("请先填写会计分录描述！");
          }
        }
      },

      delAcctEntry(record, index) {
        if (this.title == '新增会计分录' || this.title == '修改会计分录') {
          this.dataSource.splice(index, 1);
        }
      },

      handleAcctEntryAddEditClose() {
        this.acctEntryAddEdit.visiable = false
      },
      handleAcctEntryAddEditSuccess(data) {
        this.acctEntryAddEdit.visiable = false
        if ("add" == data.optFlag) {
          this.dataSource.push(data);
          if (this.paginationInfo && this.paginationInfo.pageSize) {
            this.paginationInfo.pageSize = this.paginationInfo.pageSize + 1;
          }
        } else {
          /* 通过 this.dataSource.forEach 遍历赋值后并不会通过数据双向绑定更新dataSource里的内容 */
          for (var i = 0; i < this.dataSource.length; i++) {
            if (data.groupNo == this.dataSource[i].groupNo) {
              this.dataSource[i].id = data.id;
              this.dataSource[i].instId = data.instId;
              this.dataSource[i].groupNo = data.groupNo;
              this.dataSource[i].settleRoleD = data.settleRoleD;
              this.dataSource[i].settleRoleC = data.settleRoleC;
              this.dataSource[i].settleAcctIdD = data.settleAcctIdD;
              this.dataSource[i].settleAcctIdC = data.settleAcctIdC;
              this.dataSource[i].amountDirectionD = data.amountDirectionD;
              this.dataSource[i].amountDirectionC = data.amountDirectionC;
            }
          }
        }
      },

      reset() {
        this.loading = false
        this.isCancel = false
        this.isUpd = false
        this.isStop = false
        this.title = '新增会计分录'
        this.dataSource = []
        this.optFlagTmp = 'add'
        this.form.resetFields()
      },
      onClose() {
        this.reset()
        this.$emit('close')
      },
      handleSubmit() {
        this.form.validateFields((err, values) => {
          if (!err) {
            if (this.dataSource.length == 0) {
              return this.$message.warning('请点击 [ 新增 ]按钮，增加会计分录信息！')
            }

            this.setInfoFields()
            this.loading = true
            this.dataSource.forEach((data) => {
              data.instId = this.instId
              data.acctEntryId = this.info.acctEntryId
              data.acctEntryDesc = this.info.acctEntryDesc
              data.auditStatus = this.info.auditStatus
              data.oprId = this.info.oprId
              data.oprStatus = this.info.oprStatus
              data.stopReason = this.info.stopReason
              data.cancelReason = this.info.cancelReason
            })
            let optFlag = this.optFlagTmp

            const params = {
              acctEntryList: this.dataSource,
              optFlag: optFlag,
            }

            // console.log(params)
            this.$postJson('/admin/csmc/acctEntry', params).then((r) => {
              this.reset()
              this.$emit('success')
            }).catch(() => {
              this.loading = false
            })

          }
        })
      },

      setInfoFields() {
        let values = this.form.getFieldsValue(['id', 'acctEntryId', 'acctEntryDesc', 'stopReason',
          'cancelReason', 'auditStatus', 'oprId', 'oprStatus'])
        if (typeof values !== 'undefined') {
          Object.keys(values).forEach(_key => {
            this.info[_key] = values[_key]
          })
        }
      },

      setAcctEntryFormValues({...info}) {
        let fields = ['id', 'acctEntryId', 'acctEntryDesc', 'auditStatus', 'oprId', 'oprStatus']
        this.optFlagTmp = info.operation
        if (info.operation == 'stop') {
          this.isStop = true
          this.isUpd = true
          this.title = '停用会计分录'
        } else if (info.operation == 'use') {
          this.isUpd = true
          this.title = '启用会计分录'
        } else if (info.operation == 'cancel') {
          this.isCancel = true
          this.isUpd = true
          this.title = '注销会计分录'
        } else if (info.operation == 'view') {
          this.isUpd = true
          this.title = '详情'
        } else {
          this.title = '修改会计分录'
        }
        Object.keys(info).forEach((key) => {
          if (fields.indexOf(key) !== -1) {
            this.form.getFieldDecorator(key)
            let obj = {}
            obj[key] = info[key]
            this.form.setFieldsValue(obj)
          }
        })

        this.fetch();
      },

      handleTableChange(pagination, filters, sorter) {
        // 将这三个参数赋值给Vue data，用于后续使用
        this.paginationInfo = pagination
        // 重置列过滤器规则
        this.filteredInfo = null
        // 重置列排序规则
        this.sortedInfo = sorter

        // this.reconSceneInfo.visiable = false
        this.fetch({
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...this.queryParams,
          ...filters
        })
      },
      fetch(params = {}) {
        this.loading = true
        if (this.paginationInfo) {
          // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
          this.$refs.TableInfo.pagination.current = this.paginationInfo.current
          this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
          params.pageSize = this.paginationInfo.pageSize
          params.pageNum = this.paginationInfo.current
        } else {
          // 如果分页信息为空，则设置为默认值
          params.pageSize = this.pagination.defaultPageSize
          params.pageNum = this.pagination.defaultCurrent
        }
        params.id = this.form.getFieldValue("id");
        params.acctEntryId = this.form.getFieldValue("acctEntryId");
        params.acctEntryDesc = this.form.getFieldValue("acctEntryDesc");
        if ((params.id && params.id != null && params.id.toString() != "") &&
          (this.optFlagTmp && this.optFlagTmp != null && this.optFlagTmp.toString() != "")) {
          params.optFlag = this.optFlagTmp;

          this.$get('/admin/csmc/acctEntry/searchAcctEntryData', {
            ...params
          }).then((r) => {
            let data = r.data
            console.log(data)
            this.loading = false
            this.dataSource = r.data.rows
            console.log(r.data.rows)
            const pagination = {...this.pagination}
            pagination.total = data.total
            this.pagination = pagination
          })
        } else {
          this.loading = false;
        }
      }

    }

  }
</script>
<style>
  .firstColAdd {
    text-align: right;
    margin-top: 8px;
    margin-right: 28px
  }
</style>




